package com.zzyl.nursing.service.impl;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.assist.ISqlRunner;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.core.domain.model.LoginUser;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.*;
import com.zzyl.framework.interceptor.MemberInterceptor;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.FamilyMemberAddDto;
import com.zzyl.nursing.dto.FamilyMemberMy;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.service.IElderService;
import com.zzyl.nursing.service.IFamilyMemberElderService;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.nursing.vo.FamilyMemberLostByPageVo;
import com.zzyl.nursing.vo.LoginVo;
import com.zzyl.nursing.vo.QueryDeviceDataListByDayVo;
import com.zzyl.nursing.vo.queryServicePropertiesVo;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.servlet.http.HttpServletRequest;

/**
 * 老人家属Service业务层处理
 *
 * @author ruoyi
 * @date 2025-04-26
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper,FamilyMember> implements IFamilyMemberService
{
    @Autowired
    private FamilyMemberMapper familyMemberMapper;
    @Autowired
    private IElderService elderService;
    @Autowired
    private IFamilyMemberService familyMemberService;
    @Autowired
    private FamilyMemberElderMapper familyMemberElderMapper;



    static List<String> DEFAULT_NICKNAME_PREFIX = ListUtil.of(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );
    private ElderMapper elderMapper;
    @Autowired
    private MemberInterceptor memberInterceptor;
    @Autowired
    private FamilyMemberElderServiceImpl FamilyMemberElderService;
    @Autowired
    private RoomMapper roomMapper;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    /**
     * 查询老人家属
     *
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询老人家属列表
     *
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember)
    {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember)
    {
        return save(familyMember)?1:0;
    }

    /**
     * 修改老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember)
    {
        return updateById(familyMember)?1:0;
    }

    /**
     * 批量删除老人家属
     *
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除老人家属信息
     *
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id)
    {
        return removeById(id)?1:0;
    }

    @Autowired
    private WechatService wechatService;

    @Autowired
    private TokenService tokenService;

    /**
     * 小程序端登录
     * @param dto
     * @return
     */
    @Override
    public LoginVo login(UserLoginRequestDto dto) {

        //获取openid  微信接口获取
        String openid = wechatService.getOpenid(dto.getCode());

        //根据openid查询用户信息
        FamilyMember familyMember = getOne(Wrappers.<FamilyMember>lambdaQuery().eq(FamilyMember::getOpenId, openid));

        //如果用户为空，构建用户，赋值一个openid
        if(ObjectUtil.isEmpty(familyMember)){
            familyMember = FamilyMember
                    .builder()
                    .openId(openid)
                    .build();
        }

        //获取用户的手机号  微信接口获取
        String phone = wechatService.getPhone(dto.getPhoneCode());

        //保存或更新用户
        insertOrUpdateFamilyMember(familyMember,phone);

        //生成token返回
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", familyMember.getId());
        claims.put("userName", familyMember.getName());

        String token = tokenService.createToken(claims);
        LoginVo loginVo = new LoginVo();
        loginVo.setNickName(familyMember.getName());
        loginVo.setToken(token);

        return loginVo;
    }

    /**
     * 保存或更新用户
     * @param familyMember
     * @param phone
     */
    private void insertOrUpdateFamilyMember(FamilyMember familyMember, String phone) {

        //判断手机号与数据库的手机号是否一致
        if(ObjectUtil.notEqual(familyMember.getPhone(),phone)){
            familyMember.setPhone(phone);
        }
        //判断是否存在id，如果存在id，则更新，不存在则保存
        if(ObjectUtil.isNotEmpty(familyMember.getId())){
            updateById(familyMember);
            return;
        }
        //获取用户的昵称
        int index = (int)(Math.random() * DEFAULT_NICKNAME_PREFIX.size());
        String nickName = DEFAULT_NICKNAME_PREFIX.get(index) + StringUtils.substring(phone,7,11);
        familyMember.setName(nickName);
        //保存
        save(familyMember);

    }

    /**
     * 绑定老人家属信息
     *
     * @param dto 老人信息
     */
    @Override
    public void add(FamilyMemberAddDto dto) {
        // 对老人身份证进行查询,是否存在
        LambdaQueryWrapper<Elder> eqElder = Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, dto.getIdCard())
                .eq(Elder::getName, dto.getName())
                .select(Elder::getId, Elder::getIdCardNo, Elder::getName);
        Elder elder = elderService.getOne(eqElder);
        if (elder.getIdCardNo() == dto.getIdCard() && elder.getName().equals(dto.getName())) {
            throw new BaseException("该身份证号不存在或老人姓名错误,请检查!");
        }
        // 从小程序端请求中获取当前登录用户信息
        // 从小程序端请求中获取当前登录用户信息
        Long userId = UserThreadLocal.getUserId();
        FamilyMemberElder fme = new FamilyMemberElder();
        // 老人家属id
        fme.setFamilyMemberId(userId);
        // 老人id
        fme.setElderId(elder.getId());
        // 家属对老人的称呼,放入备注字段
        fme.setRemark(dto.getRemark());
        FamilyMemberElderService.insertFamilyMemberElder(fme);
    }

    /**
     * 查询家人列表
     *
     * @return
     */
    @Override
    public List<FamilyMemberMy> my() {
        List<FamilyMemberMy> list = familyMemberElderMapper.selectFamilyMemberElderMyAll();
        list.forEach(familyMemberMy -> {
            Long elderId = familyMemberMy.getElderId();
            Elder elder = elderService.selectElderById(elderId);
            String name = elder.getName();
            familyMemberMy.setElderName(name);
        });
        return list;
    }

    /**
     * 查询家人列表,进行分页查询
     *
     * @return
     */
    @Override
    public List<FamilyMemberLostByPageVo> listByPage() {
        List<FamilyMemberMy> my = my();
        List<FamilyMemberLostByPageVo> list = new ArrayList<>();

        // 先收集所有elderId，避免循环中查询数据库
        List<Long> elderIds = my.stream()
                .map(FamilyMemberMy::getElderId)
                .distinct()
                .collect(Collectors.toList());

        // 批量查询所有elder信息
        Map<Long, Elder> elderMap = new HashMap<>();
        if (!elderIds.isEmpty()) {
            LambdaQueryWrapper<Elder> elderQuery = Wrappers.<Elder>lambdaQuery()
                    .in(Elder::getId, elderIds);
            List<Elder> elders = elderService.list(elderQuery);
            elderMap = elders.stream().collect(Collectors.toMap(Elder::getId, Function.identity()));
        }

        // 批量查询所有设备信息
        Map<Long, List<Device>> deviceMap = new HashMap<>();
        if (!elderIds.isEmpty()) {
            List<Device> allDevices = deviceMapper.selectDevicesByElderIds(elderIds);
            deviceMap = allDevices.stream()
                    .collect(Collectors.groupingBy(device -> Long.valueOf(device.getBindingLocation())));
        }

        // 处理数据映射
        for (FamilyMemberMy familyMemberMy : my) {
            FamilyMemberLostByPageVo familyMemberLostByPageVo = new FamilyMemberLostByPageVo();
            familyMemberLostByPageVo.setMid(familyMemberMy.getId().toString());
            familyMemberLostByPageVo.setMremark(familyMemberMy.getRemark());
            familyMemberLostByPageVo.setElderId(familyMemberMy.getElderId().toString());

            Elder elder = elderMap.get(familyMemberMy.getElderId());
            if (elder != null) {
                familyMemberLostByPageVo.setImage(elder.getImage());
                familyMemberLostByPageVo.setBedNumber(elder.getBedNumber());

                // 根据老人表中的床位编号获取房间信息,然后得到房间的型号
                String bedNumber = elder.getBedNumber();
                if (StringUtils.isNotEmpty(bedNumber) && bedNumber.contains("-")) {
                    String[] split = StringUtils.split(bedNumber, "-");
                    if (split.length > 0) {
                        // 使用roomMapper替代roomService
                        Room room = roomMapper.selectRoomById(Long.valueOf(split[0]));
                        if (room != null) {
                            familyMemberLostByPageVo.setTypeName(room.getTypeName());
                        }
                    }
                }

                // 设置设备信息（只设置第一个设备的信息，保持与原逻辑一致）
                List<Device> devices = deviceMap.getOrDefault(elder.getId(), Collections.emptyList());
                if (!devices.isEmpty()) {
                    Device device = devices.get(0);
                    familyMemberLostByPageVo.setIotId(device.getIotId());
                    familyMemberLostByPageVo.setDeviceName(device.getDeviceName());
                    familyMemberLostByPageVo.setProductKey(device.getProductKey());
                }
            }

            list.add(familyMemberLostByPageVo);
        }

        return list;

    }

    /**
     * 查询健康数据
     *
     * @param iotId
     * @return
     */
    @Override
    public List<queryServicePropertiesVo> queryServiceProperties(String iotId) {
        List<DeviceData> list = deviceDataMapper.selectDeviceData(iotId);
        return list.stream().map(deviceData -> {
            queryServicePropertiesVo vo = new queryServicePropertiesVo();
            vo.setFunctionId(deviceData.getFunctionId());
            vo.setEventTime(deviceData.getCreateTime().toString());
            vo.setValue(Long.parseLong(deviceData.getDataValue()));
            return vo;
        }).collect(Collectors.toList());
    }

    /**
     * @param iotId
     * @param startTime
     * @param endTime
     * @param functionId
     * @return
     */
    @Override
    public List<QueryDeviceDataListByDayVo> queryDeviceDataListByDay(String iotId, String startTime, String endTime, String functionId) {
        return null;
    }
}
